package com.zhy.usercenter.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Preconditions;
import com.zhy.usercenter.auth.DbmAuthority;
import com.zhy.usercenter.common.BaseResponse;
import com.zhy.usercenter.common.ErrorCode;
import com.zhy.usercenter.common.ResultUtils;
import com.zhy.usercenter.entity.User;
import com.zhy.usercenter.entity.UserLogin;
import com.zhy.usercenter.entity.UserRegister;
import com.zhy.usercenter.exception.BusinessException;
import com.zhy.usercenter.service.UserService;
import com.zhy.usercenter.service.UserServiceExpand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.stream.Collectors;

import static com.zhy.usercenter.common.ErrorCode.PARAMS_ERROR;
import static com.zhy.usercenter.constant.UserConstant.*;

/**
 * @author 随缘而愈
 * @version 3.0
 * @description 用户中心增强版本控制层
 * @date 22/3/2024 下午4:40
 */
@Api(tags = "用户中心增强版本")
@Slf4j
@RestController
@RequestMapping("/api/user/expand")
public class UserExpandController {

    @Resource
    private UserServiceExpand userServiceExpand;

    /**
     * 用户注册
     *
     * @param userRegister      用户注册实体类
     * @return                  自定义返回类型
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册",notes = "用户数据")
    public BaseResponse<Long> userRegister(@RequestBody UserRegister userRegister) {
        try {
            if (log.isInfoEnabled()){
                log.info("UserExpandController.userRegister.userRegister:{}", JSON.toJSONString(userRegister));
            }
            // 校验
            Preconditions.checkNotNull(userRegister.getUserAccount(),"账号不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(userRegister.getUserAccount()),"密码不能为空");
            Preconditions.checkArgument(
                    StringUtils.equals(userRegister.getUserPassword(),userRegister.getUserPassword()),
                    "二次输入密码不相同"
            );
            long result = userServiceExpand.userRegisterExpand(userRegister);
            return ResultUtils.success(result);

        }catch (Exception e){
            log.error("UserExpandController.userRegister.error:{}", e.getMessage(), e);
            return ResultUtils.error(PARAMS_ERROR,"注册失败");
        }

    }

    /**
     * 用户登录
     *
     * @param userLogin     用户登录实体类
     * @param request       请求
     * @return              自定义返回类型
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户数据")
    public BaseResponse<User> userLogin(@RequestBody UserLogin userLogin, HttpServletRequest request) {
        try {
            if (log.isInfoEnabled()){
                log.info("UserExpandController.userRegister.userLogin:{}",JSON.toJSONString(userLogin));
            }
            Preconditions.checkNotNull(userLogin.getUserAccount(),"账号不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(userLogin.getUserAccount()),"密码不能为空");
            return ResultUtils.success(userServiceExpand.userLoginExpand(userLogin,request));
        } catch (Exception e){
            log.error("UserExpandController.userRegister.userLogin:{}", e.getMessage(), e);
            return ResultUtils.error(PARAMS_ERROR,"登录失败");
        }

    }

    /**
     * 用户注销
     *
     * @param request   请求
     * @return          自定义返回类型
     */
    @PostMapping("/logout")
    @ApiOperation(value = "用户注销", notes = "请求")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(PARAMS_ERROR);
        }
        userServiceExpand.userLogout(request);
        return ResultUtils.success(0);
    }

    /**
     * 获取当前用户
     *
     * @param request    请求
     * @return           统一返回类型
     */
//    @GetMapping("/current")
//    @ApiOperation(value = "获取当前用户", notes = "请求")
//    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
//        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
//        User currentUser = (User) userObj;
//        if (currentUser == null) {
//            throw new BusinessException(ErrorCode.NOT_LOGIN);
//        }
//        long userId = currentUser.getId();
//        // TODO 校验用户是否合法
//        User user = userService.getById(userId);
//        User safetyUser = userService.getSafetyUser(user);
//        return ResultUtils.success(safetyUser);
//    }

    /**
     * 查询用户（管理员）
     * @param username   用户昵称
     * @param request    请求
     * @return           所有用户信息
     */
//    @GetMapping("/search")
//    @ApiOperation(value = "查询所有用户", notes = "用户昵称&请求")
//    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
//        if (!isAdmin(request)) {
//            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
//        }
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(username)) {
//            queryWrapper.like("username", username);
//        }
//        List<User> userList = userService.list(queryWrapper);
//        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
//        return ResultUtils.success(list);
//    }

    /**
     * 删除用户（管理员）
     * @param id        用户id
     * @param request   请求
     * @return          是否成功
    */
//    @PostMapping("/delete")
//    @ApiOperation(value = "删除用户", notes = "用户id&请求")
//    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
//        if (!isAdmin(request)) {
//            throw new BusinessException(ErrorCode.NO_AUTH);
//        }
//        if (id <= 0) {
//            throw new BusinessException(PARAMS_ERROR);
//        }
//        boolean b = userService.removeById(id);
//        return ResultUtils.success(b);
//    }

    /**
     * 更新用户（管理员）
     * @param user       用户
     * @param request   请求
     * @return          是否成功
     */
//    @DbmAuthority("功能:角色:权限") //访问这个功能登录用户所需要的角色和权限
//    @PostMapping("/update")
//    public BaseResponse<Boolean> updateUser(@RequestBody User user,HttpServletRequest request){
//        if (!isAdmin(request)){
//            throw new BusinessException(ErrorCode.NO_AUTH);
//        }
//        if (user.getId() <=0 ){
//            throw new BusinessException(PARAMS_ERROR);
//        }
//
//        //TODO 用户行为记录
//        Long userId = user.getId();
//        // 获取请求的URL
//        String requestUrl = request.getRequestURL().toString();
//        // 记录用户行为到日志或数据库
//        log.info("User {} performed action at {}", userId, requestUrl);
//
//
//        boolean result = userService.update(user);
//        return ResultUtils.success(result);
//    }


}
